//
//  PoiSearchPerKeywordController.m
//  MAMapKit_2D_Demo
//
//  Created by shaobin on 16/8/11.
//  Copyright © 2016年 Autonavi. All rights reserved.
//

#import "PoiSearchPerKeywordController.h"
#import "POIAnnotation.h"
#import "CommonUtility.h"
#import "ErrorInfoUtility.h"

@interface PoiSearchPerKeywordController ()<MAMapViewDelegate, AMapSearchDelegate, UISearchBarDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) POIAnnotation *pointAnnotation;

@end

@implementation PoiSearchPerKeywordController
#pragma mark - Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(returnAction)];
    
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	self.mapView.userTrackingMode = MAUserTrackingModeFollow;
	self.mapView.showsUserLocation = YES;
	self.mapView.zoomLevel = 16;
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
	
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    [self initSearchBar];
	
	/*
	MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
	hud.animationType = MBProgressHUDAnimationFade;
	hud.tintColor = kWhiteColor;
	hud.bezelView.backgroundColor = kBlackColor;
	hud.mode = MBProgressHUDModeText;
	hud.label.text = @"请长按地图任意位置生成标记，或在上方搜索框搜索";
	hud.label.numberOfLines = 0;
	[hud hideAnimated:YES afterDelay:2.5f];
	 
	UILongPressGestureRecognizer *lpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
	lpress.delegate = self;
	[self.mapView addGestureRecognizer:lpress];
	 */
}

#pragma mark - 
- (void)initSearchBar
{
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
    self.searchBar.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.searchBar.barStyle     = UIBarStyleDefault;
    self.searchBar.delegate     = self;
    self.searchBar.placeholder  = @"输入关键字";
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    
    self.navigationItem.titleView = self.searchBar;
    
    [self.searchBar sizeToFit];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.searchBar setShowsCancelButton:YES];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    [self.searchBar setShowsCancelButton:NO];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    
    if(self.searchBar.text.length == 0) {
        return;
    }
    
    [self searchPoiByKeyword:self.searchBar.text];
}

#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    id<MAAnnotation> annotation = view.annotation;
    
    if ([annotation isKindOfClass:[POIAnnotation class]])
    {
        POIAnnotation *poiAnnotation = (POIAnnotation*)annotation;
		
		NSDictionary *dict = @{@"poi":poiAnnotation.poi};
		//创建通知
		NSNotification *notification =[NSNotification notificationWithName:@"getLocate" object:nil userInfo:dict];
		
		//通过通知中心发送通知
		[[NSNotificationCenter defaultCenter] postNotification:notification];
		
		[self.navigationController popViewControllerAnimated:YES];
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[POIAnnotation class]])
    {
        static NSString *poiIdentifier = @"poiIdentifier";
        MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:poiIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:poiIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
		UIButton *chooseBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
		[chooseBtn setTitle:@"选择" forState:UIControlStateNormal];
		chooseBtn.backgroundColor = UIMainColorRGB;
		chooseBtn.titleLabel.font = [UIFont systemFontOfSize:12];
		[chooseBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        poiAnnotationView.rightCalloutAccessoryView = chooseBtn;
        
        return poiAnnotationView;
    }
    return nil;
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@ - %@", error, [ErrorInfoUtility errorDescriptionWithCode:error.code]);
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    if (response.pois.count == 0)
    {
        return;
    }
    
    NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
        [poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
        
    }];
    
    /* 将结果以annotation的形式加载到地图上. */
    [self.mapView addAnnotations:poiAnnotations];
    
    /* 如果只有一个结果，设置其为中心点. */
    if (poiAnnotations.count == 1)
    {
        [self.mapView setCenterCoordinate:[poiAnnotations[0] coordinate]];
    }
    /* 如果有多个结果, 设置地图使所有的annotation都可见. */
    else
    {
        [self.mapView showAnnotations:poiAnnotations animated:NO];
    }
}

#pragma mark - Utility
/* 根据关键字来搜索POI. */
- (void)searchPoiByKeyword:(NSString *)keyword
{
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords = keyword;
//    request.keywords            = @"北京大学";
//    request.city                = @"北京";
//    request.types               = @"高等院校";
//    request.requireExtension    = YES;
//    
//    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
//    request.cityLimit           = YES;
    request.requireSubPOIs      = YES;
    
    [self.search AMapPOIKeywordsSearch:request];
}

- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {
	
	AMapPOI *poi = [[AMapPOI alloc] init];
	[poi setLocation:[AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude]];
	CLLocation *location = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
	CLGeocoder *geocoder=[[CLGeocoder alloc]init];
	[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
		if (error) {
			NSLog(@"反编码失败:%@",error);
		}else {
			//NSLog(@"反编码成功:%@",placemarks);
			CLPlacemark *placemark=[placemarks lastObject];
			//NSLog(@"%@",placemark.addressDictionary[@"FormattedAddressLines"]);
			NSDictionary *addressDic=placemark.addressDictionary;
			
			NSString *state=[addressDic objectForKey:@"State"];
			NSString *city=[addressDic objectForKey:@"City"];
			NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
			NSString *street=[addressDic objectForKey:@"Street"];
			//NSLog(@"%@,%@,%@,%@",state,city,subLocality,street);
			NSString *strLocation;
			if (street.length == 0 || street == NULL || [street isEqualToString:@"(null)"]) {
				strLocation= [NSString stringWithFormat:@"%@%@%@",state,city,subLocality];
			}else{
				strLocation= [NSString stringWithFormat:@"%@%@%@%@",state,city,subLocality,street];
			}
			[poi setAddress:strLocation];
			[poi setName:@"自定义地址"];
			[self.mapView removeAnnotation:self.pointAnnotation];
			_pointAnnotation = [[POIAnnotation alloc] initWithPOI:poi];
			[self.mapView addAnnotation:self.pointAnnotation];
		}
	}];
	
	
}

#pragma mark - Handle Action

- (void)returnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)longPress:(UIGestureRecognizer*)gestureRecognizer {
	if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
		return;
	}
	[_mapView removeAnnotation:_pointAnnotation];
	//坐标转换
	CGPoint touchPoint = [gestureRecognizer locationInView:_mapView];
	CLLocationCoordinate2D touchMapCoordinate =
	[_mapView convertPoint:touchPoint toCoordinateFromView:_mapView];
	
	_pointAnnotation.coordinate = touchMapCoordinate;
	
	[_mapView addAnnotation:_pointAnnotation];
	
}
#pragma mark - 允许多手势响应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
	return YES;
}



@end
